package teach.aistar.util;

import org.springframework.web.multipart.MultipartFile;
import teach.aistar.model.vo.Images;
import teach.aistar.model.vo.Images;

import java.io.File;
import java.io.IOException;
import java.util.UUID;
@SuppressWarnings("all")
public class FileUtil {
    public static Images FileUpload(String pathName, MultipartFile file){
        Images images = new Images();
        String newName = null;
        String oldName = null;
        if(file.isEmpty()){
           images.setMessage("图片为空");
        }else{
            //与数据交互图片工具类
            //oldName为最初的文件中传入的图片名称
            oldName= file.getOriginalFilename();

             System.out.println(oldName);
            //拼接随机的图片名，后面为切割图片后缀
            newName= UUID.randomUUID().toString()+ oldName.substring(oldName.lastIndexOf("."));
            //创建存放路径的文件
            File upload = new File(pathName);
            System.out.println(upload);
            //创建文件夹
            if(!upload.exists()){
                upload.mkdirs();
            }
            try {
                //将图片存放到指定的文件里面
                File  resultPath=  new File(upload+"/"+newName);
                System.out.println(resultPath);
                file.transferTo(resultPath);
                String finalPath=resultPath.toString();
//            将图片路径放入实体类
                images.setImage(newName);
                images.setMessage("图片上传成功");
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println(images);
        }
        return images;
    }
}
